import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:wuxu_flutter_lianxi/dao/dao_result.dart';
import 'package:wuxu_flutter_lianxi/dao/local_storage.dart';
import 'package:wuxu_flutter_lianxi/env/config.dart';
import 'package:wuxu_flutter_lianxi/net/http_managert.dart';

import '../model/user.dart';
import '../net/api_urls.dart';

class UserDao {
  static UserInfo? userInfo;

  /// UserDao.initUserInfo()不是Future类，也可以使用.then? 答：async修饰的函数返回值为Future类型
  static initUserInfo() async {
    var userInfoJson = await LocalStorage.get(Config.USER_INFO);
    if (userInfoJson != null) {
      var map = json.decode(userInfoJson);
      userInfo = UserInfo.fromJson(map);
      print("initUserInfo：$userInfo");
    }
    return userInfo;
  }

  static getUserInfo() {
    return userInfo;
  }

  static clearUserInfo() {
    userInfo = null;
  }

  static login(username, password, store) async {
    String type = "$username:$password";
    //base64加密存储
    var bytes = utf8.encode(type);
    var base64String = base64.encode(bytes);
    await LocalStorage.save(Config.USER_NAME_KEY, username);
    await LocalStorage.save(Config.USER_BASIC_CODE, base64String);

    String url = "$url_host/login";
    Options option = Options(method: "post");
    var params = {"account": username, "password": password};
    var res =
        await httpManager.netFetch(url, json.encode(params), option: option);
    if (res.result && res.data != null && res.data['result'] != null) {
      userInfo = UserInfo.fromJson(res.data?['result']);
      await LocalStorage.save(Config.USER_INFO, json.encode(res.data['result']));
      print("login：$userInfo");
      return DataResult(userInfo, true);
    } else {
      return DataResult(res.data, false);
    }
  }
}
